#!/bin/sh /etc/rc.common

START=61
STOP=00

USE_PROCD=1
PROG=/usr/sbin/kresd
CONFIGFILE=/tmp/kresd/kresd.config
ROOTKEYFILE=/etc/knot-resolver/root.keys
DEFAULT_RUNDIR=/tmp/kresd
USERNAME=kresd
GROUP=kresd

init_header() {
	{
	echo "--Automatically generated file; DO NOT EDIT"
	echo "modules = {"
	echo "    'hints > iterate'"
	echo "  , 'policy'"
	if [ "$prefetch" \!= 0 ]; then
		echo "  , 'stats'"
		echo "  , predict = {"
		echo "        window = 30 -- 30 minutes sampling window"
		echo "      , period = 24*(60/30) -- track last 24 hours"
		echo "  }"
	fi
	echo "}"
	echo "hints.use_nodata(true)"
	} > $CONFIGFILE
}

init_rootkey() {
	{
	echo "trust_anchors.remove('.')"
	echo "trust_anchors.add_file('$ROOTKEYFILE', true)"
	} >> $CONFIGFILE
}

modify_rundir() {
	local rundir

	#create rundir
	rundir="$DEFAULT_RUNDIR"

	if [ ! -d "$rundir" ]; then
		mkdir -p "$rundir"
	fi

	if id "$1" >/dev/null 2>&1; then
		chown -R $USERNAME:$GROUP "$rundir"
	fi
}

start_service() {
	procd_open_instance
	procd_set_param file /etc/config/resolver
	procd_set_param command "$PROG"
	procd_append_param command --noninteractive
	procd_set_param respawn
	modify_rundir
	init_header
	init_rootkey

	# knot-resolver config
	procd_append_param command -c "$CONFIGFILE"
	procd_append_param command -a "0.0.0.0#53"
	procd_append_param command -a "::0#53"
	procd_set_param nice '-5'
	procd_close_instance
}

reload_service()
{
	stop
	start
}
